package com.example.asynctaskdemo.observer;

import java.util.Iterator;

/**
 * Created by Kellan on 2016/12/3.
 */
public class ObserverManager<T> {
    private WeakContainer<UpdateListener> mSocialCallback = null;

    private ObserverManager() {
    }

    public static ObserverManager getInstance() {
        return LocHolder.instance;
    }

    public void addListener(UpdateListener cb) {
        if (cb != null) {
            if (mSocialCallback == null) {
                mSocialCallback = new WeakContainer<>();
            }
            mSocialCallback.add(cb);
        }
    }

    public void noticeAll(int type, T o) {
        if (mSocialCallback == null || mSocialCallback.size() == 0)
            return;

        Iterator<UpdateListener> iterator = mSocialCallback.iterator();
        while (iterator.hasNext()) {
            UpdateListener cb = iterator.next();
            if (cb == null) {
                iterator.remove();
            } else {
                cb.update(type, o);
            }
        }
    }

    public void removeListener(UpdateListener cb) {
        if (mSocialCallback != null) {
            mSocialCallback.remove(cb);
        }
    }

    public interface UpdateListener<T> {
        void update(int type, T o);
    }

    private static class LocHolder {
        private static final ObserverManager instance = new ObserverManager();
    }
}
